package com.rednose.videoplayer.activities;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.PictureInPictureParams;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.audiofx.AudioEffect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Rational;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.google.android.exoplayer2.PlaybackParameters;
import com.rednose.videoplayer.dialogs.BrightnessDialog;
import com.rednose.videoplayer.model.IconModel;
import com.rednose.videoplayer.model.MediaFiles;
import com.rednose.videoplayer.adapters.PlaybackIconsAdapter;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ConcatenatingMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.rednose.videoplayer.dialogs.PlaylistDialog;
import com.rednose.videoplayer.R;
import com.rednose.videoplayer.adapters.VideoFilesAdapter;
import com.rednose.videoplayer.dialogs.VolumeDialog;

import java.io.File;
import java.util.ArrayList;

public class VideoPlayerActivity extends AppCompatActivity implements View.OnClickListener {

    ArrayList<MediaFiles> mVideoFiles = new ArrayList<>();
    PlayerView playerView;
    SimpleExoPlayer player;
    int position;
    String videoTitle;
    TextView title;
    private ControlsMode controlsMode;              //控制模式

    public enum ControlsMode {                      //控制模式枚举
        LOCK, FULLSCREEN
    }

    ImageView videoBack, lock, unlock, scaling, videoList, videoMore;       //返回按钮,锁定按钮,解锁按钮,缩放按钮,视频列表按钮,更多按钮
    VideoFilesAdapter videoFilesAdapter;                                  //视频文件适配器
    RelativeLayout root;                                    //根布局
    ConcatenatingMediaSource concatenatingMediaSource;
    ImageView nextButton, previousButton;
    private ArrayList<IconModel> iconModelArrayList = new ArrayList<>();        //图标模型列表
    PlaybackIconsAdapter playbackIconsAdapter;                                  //播放图标适配器
    RecyclerView recyclerViewIcons;                                             //图标列表
    boolean expand = false;                                                     //是否展开
    View nightMode;                                                             //夜间模式
    boolean dark = false;                                                       //是否黑暗
    boolean mute = false;                                                       //是否静音
    PlaybackParameters parameters;                                              //播放参数
    float speed;

/*    DialogProperties dialogProperties;
    FilePickerDialog filePickerDialog;*/

    Uri uriSubtitle;
    PictureInPictureParams.Builder pictureInPicture;
    boolean isCrossChecked;
    FrameLayout eqContainer;
    //horizontal recyclerview variables

    //swipe and zoom variables
    private int device_height, device_width, brightness, media_volume;
    boolean start = false;
    boolean left, right;
    private float baseX, baseY;
    boolean swipe_move = false;
    private long diffX, diffY;
    public static final int MINIMUM_DISTANCE = 100;
    boolean success = false;
    TextView vol_text, brt_text, total_duration;
    ProgressBar vol_progress, brt_progress;
    LinearLayout vol_progress_container, vol_text_container, brt_progress_container, brt_text_container;
    ImageView vol_icon, brt_icon;
    AudioManager audioManager;
    private ContentResolver contentResolver;
    private Window window;
    boolean singleTap = false;

    RelativeLayout zoomLayout;
    RelativeLayout zoomContainer;
    TextView zoom_perc;
    ScaleGestureDetector scaleGestureDetector;
    private float scale_factor = 1.0f;
    boolean double_tap = false;
    RelativeLayout double_tap_playpause;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setFullScreen();                                    //设置全屏
        setContentView(R.layout.activity_video_player);
        getSupportActionBar().hide();                       //
        playerView = findViewById(R.id.exoplayer_view);     //初始化播放器视图
        position = getIntent().getIntExtra("position", 1);      //获取点击的视频位置,默认为1
        videoTitle = getIntent().getStringExtra("video_title");            //获取视频标题
        mVideoFiles = getIntent().getExtras().getParcelableArrayList("videoArrayList");    //获取视频列表

        initViews();
        playVideo();

        DisplayMetrics displayMetrics = new DisplayMetrics();                       //创建显示度量
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);         //获取默认显示,并设置显示度量
        device_width = displayMetrics.widthPixels;                                  //获取屏幕宽度
        device_height = displayMetrics.heightPixels;                                //获取屏幕高度




        //
/*        playerView.setOnTouchListener(new OnSwipeTouchListener(this){
            public boolean onTouch(View view, MotionEvent motionEvent){
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    start = true;
                    if (motionEvent.getX() < (device_width / 2)) {
                        left = true;
                        right = false;
                    } else if (motionEvent.getX() > (device_width / 2)) {
                        left = false;
                        right = true;
                    }
                    baseX = motionEvent.getX();                                     //获取X坐标
                    baseY = motionEvent.getY();                                     //获取Y坐标
                } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
                    swipe_move = true;
                    diffX = (long) Math.ceil(motionEvent.getX() - baseX);           //获取X坐标差,并向上取整
                    diffY = (long) Math.ceil(motionEvent.getY() - baseY);           //获取Y坐标差,并向上取整
                    double brightnessSpeed = 0.01;                               //设置亮度速度
                    if (Math.abs(diffY) > MINIMUM_DISTANCE){                    //如果Y坐标差大于最小距离
                        start = true;
                        if (Math.abs(diffY) > Math.abs(diffX)){                         //如果Y坐标差大于X坐标差
                            boolean value;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                                value = android.provider.Settings.System.canWrite(getApplicationContext());  //获取是否可以写入系统设置，如果可以则返回true
                                if (value){
                                    if (left) {
                                        contentResolver = getContentResolver();
                                        window = getWindow();
                                        try {
                                            android.provider.Settings.System.putInt(contentResolver, android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE,
                                                    android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
                                            brightness = android.provider.Settings.System.getInt(contentResolver, android.provider.Settings.System.SCREEN_BRIGHTNESS);
                                        } catch (
                                                android.provider.Settings.SettingNotFoundException e) {
                                            e.printStackTrace();
                                        }
                                        int new_brightness = (int) (brightness - (diffY * brightnessSpeed));
                                        if (new_brightness > 250) {
                                            new_brightness = 250;
                                        } else if (new_brightness < 1) {
                                            new_brightness = 1;
                                        }

                                        double brt_percentage = Math.ceil((((double) new_brightness / (double) 250) * (double) 100));
                                        brt_progress_container.setVisibility(View.VISIBLE);
                                        brt_text_container.setVisibility(View.VISIBLE);
                                        brt_progress.setProgress((int) brt_percentage);

                                        if (brt_percentage < 30) {
                                            brt_icon.setImageResource(R.drawable.ic_brightness_low);
                                        } else if (brt_percentage > 30 && brt_percentage < 80) {
                                            brt_icon.setImageResource(R.drawable.ic_brightness_moderate);
                                        } else if (brt_percentage > 80) {
                                            brt_icon.setImageResource(R.drawable.ic_brightness);
                                        }

                                        brt_text.setText(" " + (int) brt_percentage + "%");
                                        android.provider.Settings.System.putInt(contentResolver, android.provider.Settings.System.SCREEN_BRIGHTNESS,
                                                (new_brightness));
                                        WindowManager.LayoutParams layoutParams = window.getAttributes();
                                        layoutParams.screenBrightness = brightness / (float) 255;
                                        window.setAttributes(layoutParams);
                                    } else if (right) {
                                        vol_text_container.setVisibility(View.VISIBLE);
                                        media_volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                                        int maxVol = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                                        double cal = (double) diffY * ((double) maxVol / ((double) (device_height * 2) - brightnessSpeed));
                                        int newMediaVolume = media_volume - (int)  cal;
                                        if (newMediaVolume > maxVol) {
                                            newMediaVolume = maxVol;
                                        } else if (newMediaVolume < 1) {
                                            newMediaVolume = 0;
                                        }
                                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                                                newMediaVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                        double volPer = Math.ceil((((double) newMediaVolume / (double) maxVol) * (double) 100));
                                        vol_text.setText(" " + (int) volPer + "%");
                                        if (volPer < 1) {
                                            vol_icon.setImageResource(R.drawable.ic_volume_off);
                                            vol_text.setVisibility(View.VISIBLE);
                                            vol_text.setText("Off");
                                        } else if (volPer >= 1) {
                                            vol_icon.setImageResource(R.drawable.ic_volume);
                                            vol_text.setVisibility(View.VISIBLE);
                                        }
                                        vol_progress_container.setVisibility(View.VISIBLE);
                                        vol_progress.setProgress((int) volPer);
                                    }
                                   success = true;
                                }else {
                                    Toast.makeText(getApplicationContext(), "允许滑动控件的写入设置", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                                    intent.setData(Uri.parse("package:" + getPackageName()));
                                    startActivityForResult(intent, 111);                //启动Activity
                                }
                            }
                        }
                    }
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    swipe_move = false;
                    start = false;
                    vol_progress_container.setVisibility(View.GONE);
                    brt_progress_container.setVisibility(View.GONE);
                    vol_text_container.setVisibility(View.GONE);
                    brt_text_container.setVisibility(View.GONE);

                }
                return super.onTouch(view, motionEvent);
            }

            @Override
            public void onDoubleTouch() {
                super.onDoubleTouch();
            }

            @Override
            public void onSingleTouch() {
                super.onSingleTouch();
                if (singleTap) {
                    playerView.showController();
                    singleTap = false;
                } else {
                    playerView.hideController();
                    singleTap = true;
                }
            }
        });*/

        horizontalIconList();

    }

    private void horizontalIconList() {
        iconModelArrayList.add(new IconModel(R.drawable.ic_right, ""));
        iconModelArrayList.add(new IconModel(R.drawable.ic_pip_mode, "夜间模式"));
        iconModelArrayList.add(new IconModel(R.drawable.ic_pip_mode, "窗口"));
        iconModelArrayList.add(new IconModel(R.drawable.ic_equalizer, "均衡器"));
        iconModelArrayList.add(new IconModel(R.drawable.ic_rotate, "旋转"));

        playbackIconsAdapter =  new PlaybackIconsAdapter(iconModelArrayList,this) ;   //创建播放图标适配器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this,
                RecyclerView.HORIZONTAL, true);                                //创建线性布局管理器
        recyclerViewIcons.setLayoutManager(layoutManager);
        recyclerViewIcons.setAdapter(playbackIconsAdapter);
        playbackIconsAdapter.notifyDataSetChanged();

        playbackIconsAdapter.setOnItemClickListener(new PlaybackIconsAdapter.OnItemClickListener(){
            @Override
            public void onItemClick(int position) {
                if (position == 0) {
                    if (expand){
                        iconModelArrayList.clear();
                        iconModelArrayList.add(new IconModel(R.drawable.ic_right, ""));
                        iconModelArrayList.add(new IconModel(R.drawable.ic_pip_mode, "夜间模式"));
                        iconModelArrayList.add(new IconModel(R.drawable.ic_pip_mode, "窗口"));
                        iconModelArrayList.add(new IconModel(R.drawable.ic_equalizer, "均衡器"));
                        iconModelArrayList.add(new IconModel(R.drawable.ic_rotate, "旋转"));
                        playbackIconsAdapter.notifyDataSetChanged();                                //通知适配器数据已更改
                        expand = false;
                    }else {
                        if (iconModelArrayList.size() ==5 ) {
                            iconModelArrayList.add(new IconModel(R.drawable.ic_volume_off, "静音"));
                            iconModelArrayList.add(new IconModel(R.drawable.ic_volume, "音量"));
                            iconModelArrayList.add(new IconModel(R.drawable.ic_brightness, "亮度"));
                            iconModelArrayList.add(new IconModel(R.drawable.ic_speed, "播放速度"));
                            /*iconModelArrayList.add(new IconModel(R.drawable.ic_subtitle, "字幕"));*/
                        }
                        iconModelArrayList.set(position, new IconModel(R.drawable.ic_left, ""));
                        playbackIconsAdapter.notifyDataSetChanged();                                        //通知适配器数据已更改
                        expand = true;
                    }
                }
                if (position == 1) {
                    //设置夜间模式
                    if (dark) {
                        nightMode.setVisibility(View.GONE);                     //设置夜间模式不可见
                        iconModelArrayList.set(position, new IconModel(R.drawable.ic_night_mode, "夜间模式"));  //设置图标模型列表
                        playbackIconsAdapter.notifyDataSetChanged();
                        dark = false;
                    } else {
                        nightMode.setVisibility(View.VISIBLE);                  //设置夜间模式可见
                        iconModelArrayList.set(position, new IconModel(R.drawable.ic_night_mode, "白天模式"));  //设置图标模型列表
                        playbackIconsAdapter.notifyDataSetChanged();
                        dark = true;
                    }
                }
                if (position == 2) {
                    //窗口播放
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        Rational aspectRatio = new Rational(16, 9);
                        pictureInPicture.setAspectRatio(aspectRatio);
                        enterPictureInPictureMode(pictureInPicture.build());
                    } else {
                        Log.wtf("not oreo", "yes");                                 //打印警告
                    }

                }
                if (position == 3) {
                    //均衡器
                    Intent intent = new Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL);  //创建一个Intent对象,用于显示音频效果控制面板
                    if ((intent.resolveActivity(getPackageManager()) != null)) {                          //如果有Activity能够响应该Intent
                        startActivityForResult(intent, 123);                                  //启动Activity,并获取结果,请求码为123
                    } else {
                        Toast.makeText(VideoPlayerActivity.this, "没有找到均衡器", Toast.LENGTH_SHORT).show();  //提示用户
                    }
                    playbackIconsAdapter.notifyDataSetChanged();                                    //通知适配器数据已更改
                }
                if (position == 4) {
                    //旋转
                    //如果屏幕方向为竖屏，则设置为横屏； 如果屏幕方向为横屏，则设置为竖屏
                    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {  //如果屏幕方向为竖屏，则设置为横屏
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        playbackIconsAdapter.notifyDataSetChanged();
                    } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                        playbackIconsAdapter.notifyDataSetChanged();
                    }
                }
                if (position == 5) {
                    //静音模式
                    if (mute) {
                        player.setVolume(100);                                                      //设置音量
                        iconModelArrayList.set(position, new IconModel(R.drawable.ic_volume_off, "静音"));
                        playbackIconsAdapter.notifyDataSetChanged();
                        mute = false;
                    } else {
                        player.setVolume(0);                                                        //设置音量
                        iconModelArrayList.set(position, new IconModel(R.drawable.ic_volume, "解除静音"));
                        playbackIconsAdapter.notifyDataSetChanged();
                        mute = true;
                    }
                }
                if (position == 6) {
                    //音量控制
                    VolumeDialog volumeDialog = new VolumeDialog();          //创建音量对话框
                    volumeDialog.show(getSupportFragmentManager(), "dialog");  //显示音量对话框
                    playbackIconsAdapter.notifyDataSetChanged();


                }
                if (position == 7) {
                    //亮度调节
                    BrightnessDialog brightnessDialog = new BrightnessDialog();
                    brightnessDialog.show(getSupportFragmentManager(), "dialog");
                    playbackIconsAdapter.notifyDataSetChanged();
                }
                if (position == 8) {
                    //播放速度

                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(VideoPlayerActivity.this);
                    alertDialog.setTitle("选择播放速度").setPositiveButton("确定", null);
                    String[] items = {"0.5x", "1.0x ", "1.25x", "1.5x", "2x"};            //设置播放速度
                    int checkedItem = -1;                                                     //设置选中项

                    alertDialog.setSingleChoiceItems(items, checkedItem, (dialog, which) -> {       //设置单选列表项
                        switch (which) {
                            case 0:
                                speed = 0.5f;                                               //设置播放速度为0.5
                                parameters = new PlaybackParameters(speed);                 //创建播放参数
                                player.setPlaybackParameters(parameters);                   //设置播放参数
                                break;
                            case 1:
                                speed = 1.0f;                                               //设置播放速度为1.0
                                parameters = new PlaybackParameters(speed);
                                player.setPlaybackParameters(parameters);
                                break;
                            case 2:
                                speed = 1.25f;                                              //设置播放速度为1.25
                                parameters = new PlaybackParameters(speed);
                                player.setPlaybackParameters(parameters);
                                break;
                            case 3:
                                speed = 1.5f;                                               //设置播放速度为1.5
                                parameters = new PlaybackParameters(speed);
                                player.setPlaybackParameters(parameters);
                                break;
                            case 4:
                                speed = 2.0f;                                               //设置播放速度为2.0
                                parameters = new PlaybackParameters(speed);
                                player.setPlaybackParameters(parameters);
                                break;
                            default:
                                break;
                        }
                    });
                    AlertDialog alert = alertDialog.create();
                    alert.show();
                }
            }
        });
    }

    private void initViews() {
        nextButton = findViewById(R.id.exo_next);            //初始化下一个按钮
        previousButton = findViewById(R.id.exo_prev);        //初始化上一个按钮
        title = findViewById(R.id.video_title);          //初始化标题
        videoBack = findViewById(R.id.video_back);          //初始化返回按钮
        lock =  findViewById(R.id.lock);                //初始化锁定按钮
        scaling = findViewById(R.id.scaling);           //初始化缩放按钮
        unlock =  findViewById(R.id.unlock);              //初始化解锁按钮
        videoList = findViewById(R.id.video_list);        //初始化视频列表按钮
        root = findViewById(R.id.root_layout);                 //初始化根布局
        recyclerViewIcons = findViewById(R.id.recyclerview_icon);       //初始化图标列表
        nightMode = findViewById(R.id.night_mode);                    //初始化夜间模式

        vol_text = findViewById(R.id.vol_text);                     //初始化音量文本
        brt_text = findViewById(R.id.brt_text);                     //初始化亮度文本
        vol_progress = findViewById(R.id.vol_progress);             //初始化音量进度条
        brt_progress = findViewById(R.id.brt_progress);             //初始化亮度进度条
        vol_progress_container = findViewById(R.id.vol_progress_container); //初始化音量进度条容器
        brt_progress_container = findViewById(R.id.brt_progress_container); //初始化亮度进度条容器
        vol_text_container = findViewById(R.id.vol_text_container);     //初始化音量文本容器
        brt_text_container = findViewById(R.id.brt_text_container);     //初始化亮度文本容器

        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);  //获取音频管理器

        title.setText(videoTitle);                      //设置标题

        nextButton.setOnClickListener(this);              //设置下一个按钮点击事件
        previousButton.setOnClickListener(this);          //设置上一个按钮点击事件
        videoBack.setOnClickListener(this);               //设置返回按钮点击事件
        lock.setOnClickListener(this);                    //设置锁定按钮点击事件
        unlock.setOnClickListener(this);                  //设置解锁按钮点击事件
        videoList.setOnClickListener(this);               //设置视频列表按钮点击事件
        scaling.setOnClickListener(firstListener);         //设置缩放按钮点击事件

        //设置图标模型列表,并设置图标适配器
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            pictureInPicture = new PictureInPictureParams.Builder();
        }
    }

    private void playVideo() {
        String Path = mVideoFiles.get(position).getPath();    //获取视频路径
        Uri uri = Uri.parse(Path);                            //将路径转换为Uri
        player = new SimpleExoPlayer.Builder(this).build();     //创建播放器
        DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(
                this, Util.getUserAgent(this, "app"));     //创建数据源工厂
        concatenatingMediaSource = new ConcatenatingMediaSource();
        for (int i = 0; i < mVideoFiles.size(); i++) {                                  //遍历视频列表
            new File(String.valueOf(mVideoFiles.get(i)));                               //创建文件
            MediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)     //创建媒体源,并设置数据源工厂
                    .createMediaSource(Uri.parse(String.valueOf(uri)));
            concatenatingMediaSource.addMediaSource(mediaSource);                               //添加媒体源
        }

        playerView.setPlayer(player);                                   //设置播放器
        playerView.setKeepScreenOn(true);                               //保持屏幕常亮
        player.setPlaybackParameters(parameters);                   //设置播放参数

        player.prepare(concatenatingMediaSource);                       //准备播放
        player.seekTo(position, C.TIME_UNSET);                          //跳转到指定位置
        //player.setPlayWhenReady(true);                        // 确保播放器在准备好后开始播放
        playError();
    }

    //获取视频的宽高比,并设置屏幕方向，如果视频宽大于高，则设置为横屏，否则设置为竖屏
    private void screenOrientation() {
        try {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();                        //创建媒体元数据检索器
            Bitmap bitmap;                                                                          //位图
            String path = mVideoFiles.get(position).getPath();                                      //获取视频路径
            Uri uri = Uri.parse(path);
            retriever.setDataSource(this, uri);
            bitmap = retriever.getFrameAtTime();                                                    //获取视频帧

            int videoWidth = bitmap.getWidth();                                                     //获取视频宽度
            int videoHeight = bitmap.getHeight();                                                   //获取视频高度
            if (videoWidth > videoHeight) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);                 //设置屏幕方向为横屏
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);                  //设置屏幕方向为竖屏
            }

        } catch (Exception e) {
            Log.e("MediaMetaDataRetriever", "screenOrientation: ");                     //打印异常
        }
    }

    //播放错误,提示用户,并继续播放,不退出
    private void playError() {
        player.addListener(new Player.EventListener() {
            @Override
            public void onPlayerError(ExoPlaybackException error) {
                Toast.makeText(VideoPlayerActivity.this, "视频播放错误", Toast.LENGTH_SHORT).show();
            }
        });
        player.setPlayWhenReady(true);

    }

    public void onBackPressed() {
        super.onBackPressed();
        if (player.isPlaying()) {
            player.stop();
        }
    }

    @Override   //暂停播放
    protected void onPause() {
        super.onPause();
        player.setPlayWhenReady(false);     //暂停播放
        player.getPlaybackState();          //获取播放状态
        if (isInPictureInPictureMode()) {               //如果是画中画模式,则设置屏幕方向为横屏
            player.setPlayWhenReady(true);
        } else {
            player.setPlayWhenReady(false);
            player.getPlaybackState();
        }
    }

    @Override   //继续播放
    protected void onResume() {
        super.onResume();
        player.setPlayWhenReady(true);      //继续播放
        player.getPlaybackState();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        player.setPlayWhenReady(true);      //继续播放
        player.getPlaybackState();
    }

    private void setFullScreen() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);                      //隐藏标题栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,    //设置全屏
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.video_back) {
            if (player != null) {
                player.release();
            }
            finish();
        }else if (v.getId() == R.id.video_list) {
            PlaylistDialog playlistDialog = new PlaylistDialog(mVideoFiles, videoFilesAdapter);     //创建播放列表对话框
            playlistDialog.show(getSupportFragmentManager(), playlistDialog.getTag());              //显示播放列表对话框
        }else if (v.getId() == R.id.lock) {
            controlsMode = ControlsMode.FULLSCREEN;                             //设置控制模式为全屏
            root.setVisibility(View.VISIBLE);                                   //设置根布局可见
            lock.setVisibility(View.INVISIBLE);                                 //设置锁定按钮不可见
            Toast.makeText(this, "屏幕已解锁", Toast.LENGTH_SHORT).show();        //提示用户
        }else if (v.getId() == R.id.unlock) {
            controlsMode = ControlsMode.LOCK;                                   //设置控制模式为锁定
            root.setVisibility(View.INVISIBLE);                                 //设置根布局不可见
            lock.setVisibility(View.VISIBLE);                                   //设置锁定按钮可见
            Toast.makeText(this, "屏幕已锁定", Toast.LENGTH_SHORT).show();      //提示用户
        }else if (v.getId() == R.id.exo_next) {
            try {
                player.stop();
                position++;
                playVideo();
                title.setText(mVideoFiles.get(position).getDisplayName());
            }catch (Exception e) {
                Toast.makeText(this, "这已是最后一个视频", Toast.LENGTH_SHORT).show();
                finish();
            }
        }else if (v.getId() == R.id.exo_prev) {
            try {
                player.stop();
                position--;
                playVideo();
                title.setText(mVideoFiles.get(position).getDisplayName());
            }catch (Exception e) {
                Toast.makeText(this, "这已是第一个视频", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

/*        switch (v.getId()) {
            case R.id.exo_next:
                try {
                    player.stop();
                    position++;
                    playVideo();
                    title.setText(mVideoFiles.get(position).getDisplayName());
                } catch (Exception e) {
                    Toast.makeText(this, "这已是第一个视频", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            case R.id.exo_prev:
                try {
                    player.stop();
                    position--;
                    playVideo();
                    title.setText(mVideoFiles.get(position).getDisplayName());
                } catch (Exception e) {
                    Toast.makeText(this, "这已是最后一个视频", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
        }*/
    }

    //这是缩放按钮的点击事件，用于切换视频的缩放模式，点击后设置视频缩放模式为填充
    View.OnClickListener firstListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FILL);          //设置视频缩放模式为填充
            player.setVideoScalingMode(C.VIDEO_SCALING_MODE_DEFAULT);                   //设置视频缩放模式为默认
            scaling.setImageResource(R.drawable.fullscreen);                            //设置缩放按钮图片为全屏

            Toast.makeText(VideoPlayerActivity.this, "填充", Toast.LENGTH_SHORT).show();
            scaling.setOnClickListener(secondListener);                          //设置缩放按钮点击事件
        }
    };

    //这是缩放按钮的点击事件，用于切换视频的缩放模式，点击后设置视频缩放模式为缩放
    View.OnClickListener secondListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM);      //设置视频缩放模式为缩放
            player.setVideoScalingMode(C.VIDEO_SCALING_MODE_DEFAULT);               //设置视频缩放模式为默认
            scaling.setImageResource(R.drawable.zoom);                              //设置缩放按钮图片为缩放

            Toast.makeText(VideoPlayerActivity.this, "缩放", Toast.LENGTH_SHORT).show();
            scaling.setOnClickListener(thirdListener);
        }
    };

    //这是缩放按钮的点击事件，用于切换视频的缩放模式，点击后设置视频缩放模式为适应
    View.OnClickListener thirdListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            playerView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);   //设置视频缩放模式为适应
            player.setVideoScalingMode(C.VIDEO_SCALING_MODE_DEFAULT);           //设置视频缩放模式为默认
            scaling.setImageResource(R.drawable.fit);                           //设置缩放按钮图片为适应

            Toast.makeText(VideoPlayerActivity.this, "自适应", Toast.LENGTH_SHORT).show();
            scaling.setOnClickListener(firstListener);
        }
    };

    //这是缩放按钮的点击事件，用于切换视频的缩放模式，点击后设置视频缩放模式为填充
    public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) {
        super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
        isCrossChecked = isInPictureInPictureMode;
        if (isInPictureInPictureMode) {
            playerView.hideController();                            //隐藏控制器
        } else {
            playerView.showController();                            //显示控制器
        }
    }
    //
    protected void onStop() {
        super.onStop();
        if (isCrossChecked) {
            player.release();
            finish();
        }
    }

    //这是音量对话框的返回结果，用于获取音量控制权限，如果有权限，则设置音量，否则提示用户
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 111) {
            boolean value;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                value = android.provider.Settings.System.canWrite(getApplicationContext());
                if (value) {
                    success = true;
                } else {
                    Toast.makeText(getApplicationContext(), "未授予", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
